import 'package:fluent_ui/fluent_ui.dart';
import 'package:flutter/material.dart' show DataCell, DataColumn;
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:go_router/go_router.dart';
import 'package:multi_select_flutter/multi_select_flutter.dart';
import 'package:provider/provider.dart';

import '../../components/buttons.dart';
import '../../components/data_table.dart';
import '../../model/school_model.dart';
import '../../route/router.dart';
import '../../utils/date_utils.dart';
import '../app/app_dict_data.dart';
import 'school_view_model.dart';

class SchoolViewList extends StatefulWidget {
  const SchoolViewList({super.key});

  @override
  State<SchoolViewList> createState() => _SchoolViewListState();
}

class _SchoolViewListState extends State<SchoolViewList> {
  final queryFormKey = GlobalKey<FormState>();
  final tableKey = GlobalKey<DataTableState<SchoolItemRes>>();

  @override
  void initState() {
    super.initState();
    //加载数据
    final model = context.read<SchoolViewModel>();
    model.loadInit(afterHandler: () => query(model));
  }

  void query(final SchoolViewModel model) => model.query();

  Widget buildQueryForm(final SchoolViewModel model) {
    Widget buildField(SchoolQueryField field,
        Widget Function(TextEditingController? c, String label) handler) {
      final label = field.label;
      final controller = model.getController(field);
      final child = handler.call(controller, label);
      return SizedBox(
        width: 128.w,
        child: InfoLabel(label: label, child: child),
      );
    }

    Widget buildStagesField() {
      final field = SchoolQueryField.stages;
      final label = field.label;
      final c = model.getController(field);
      final child = MultiSelectDialogField<int>(
        title: Text(label),
        buttonText: Text(label),
        items: model.stageOpts,
        listType: MultiSelectListType.CHIP,
        initialValue: model.stageSplits(c?.text),
        onConfirm: (vals) => c?.text = model.stageJoins(vals),
      );
      return SizedBox(width: 192.w, child: child);
    }

    return Form(
      key: queryFormKey,
      child: Wrap(
        spacing: 5.w,
        children: [
          //名称/标题
          buildField(
            SchoolQueryField.name,
            (c, label) => TextFormBox(
              controller: c,
              placeholder: label,
            ),
          ),
          //学段集合
          buildStagesField(),
          //状态
          buildField(
            SchoolQueryField.status,
            (c, label) => ComboboxFormField(
              placeholder: Text(label),
              items: model.statusOpts,
              onChanged: (val) => c?.text = val ?? '',
            ),
          ),
        ],
      ),
    );
  }

  Widget buildQueryBars(final SchoolViewModel model) => Wrap(
        spacing: 2.w,
        children: [
          //查询
          buttons.query(onPressed: () => query(model)),
          //重置
          buttons.reset(onPressed: () {
            queryFormKey.currentState?.reset();
            model.cleanQueryFields();
            query(model);
          }),
          //新增
          buttons.add(onPressed: () => editHandler(model, null)),
        ],
      );

  void editHandler(final SchoolViewModel model, final String? id) async {
    final ret = await context.pushNamed<bool>(
      getRoteName(AppRote.schoolEdit),
      queryParameters: {'id': id ?? ''},
    );
    if (ret ?? false) {
      //查询数据
      query(model);
    }
  }

  @override
  Widget build(final BuildContext context) => Consumer<SchoolViewModel>(
        builder: (context, model, _) => ScaffoldPage.scrollable(
          header: Column(
            children: [
              PageHeader(title: const Text('学校')),
              Padding(
                padding: () {
                  final padding = PageHeader.horizontalPadding(context);
                  return EdgeInsetsDirectional.symmetric(horizontal: padding);
                }(),
                child: Row(
                  children: [
                    //查询条件
                    buildQueryForm(model),
                    //占位
                    Expanded(child: Container()),
                    //查询按钮
                    buildQueryBars(model),
                  ],
                ),
              ),
              SizedBox(height: 15.h),
            ],
          ),
          children: [
            //数据列表
            buildTable(model),
          ],
        ),
      );

  Widget buildTable(final SchoolViewModel model) {
    final labels = <String>['名称', '学段', '状态', '创建时间', '操作'];
    DataCell buildCell(String? Function() handler) => DataCell(Text(
          handler.call() ?? '',
          softWrap: false,
          overflow: TextOverflow.ellipsis,
        ));
    return DataTable<SchoolItemRes>(
      key: tableKey,
      model: model.queryModel,
      columns: labels.map((label) => DataColumn(label: Text(label))).toList(),
      onLoadData: () => query(model),
      onRowCallback: (row) => [
        //名称
        buildCell(() => row.name),
        //学段
        buildCell(() => appDictData.getLabels('stage', row.stages)),
        //状态
        buildCell(() => appDictData.getLabel('status', row.status)),
        //创建时间
        buildCell(() => dateUtils.format('yyyy-MM-dd HH:mm:ss', row.createdAt)),
        //操作
        DataCell(
          OverflowBar(
            spacing: 2.w,
            children: [
              //修改
              buttons.modify(onPressed: () {
                final id = row.id;
                if (id.isNotEmpty) {
                  editHandler(model, id);
                }
              }),
              //删除
              buttons.delete(onPressed: () {
                final id = row.id;
                if (id.isNotEmpty) {
                  model.onDeleteHandler(id);
                }
              }),
            ],
          ),
        ),
      ],
    );
  }
}
